<?php require_once 'httpFilter.php'; 'conf.php'; ?>
<?php
require_once "services/budgetServices.php";
$budgetServices = new BudgetService;


$uploadFileName = $_FILES['transactionFile']['tmp_name'];
$file = fopen($_FILES['transactionFile']['tmp_name'], "r") or exit("Unable to open file!");

$accountId = $budgetServices->getSavingsAccountId($_SESSION["userid"]);

$errCode = 0;
$duplicateCheckMap = array();

$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
if (!$con) {
	die('Could not connect: ' . mysql_error());
}

mysql_select_db(GlobalConfig::db_name, $con);

$dateFound = false;

while(!feof($file)){

	$aline = fgets($file);
	error_log($aline);


	if (strlen(strstr($aline,"Balance:"))>0) {
		error_log("IN BALANCE FOUND");
		$line =  split(",", $aline);
		$statementBal = $line[1];
		//We update the statement balance
		$query = "update account set stmtBalance=". $statementBal ." where id= ". $accountId;
		error_log($query);
		$result = mysql_query($query) or die(mysql_error());
		if (!$result) {
			$errCode = $query;
		}
		
		$availableBal = $line[2];
		//We update the available balance
		$query = "update account set available=". $availableBal ." where id= ". $accountId;
		error_log($query);
		$result = mysql_query($query) or die(mysql_error());
		if (!$result) {
			$errCode = 1;
		}
	}

	if ($dateFound){
		error_log("IN DATE FOUND");

		$line =  split(",", $aline);
			
		$hashkey = md5($line[0].$line[1].$line[2].$line[3]);
			
		$dateArray = split("/", $line[0]);
		$date = $dateArray[0]. "-".$dateArray[1]."-".$dateArray[2];
			
		$query = "insert into transaction (accountId, date, amount, description, reconciled, categoryId, bankRef, hashkey) values (". $accountId .", '". $date ."', ". $line[1] .", '". $line[3] ."', 0, 4, '". $line[3] ."', '". $hashkey ."')";

		if ($line[3] != ""){
			if($duplicateCheckMap[$line[1].":".$line[2]]){
				error_log("duplicate: " . $line[1].":".$line[2]);
			}

			error_log($query);
			$duplicateCheckMap[$line[1].":".$line[2]]=true;
			$result = mysql_query($query);

		}
			
	}

	if (strlen(strstr($aline,"Date"))>0) {
		$dateFound = true;
	}

}

fclose($file);
mysql_close($con);
?>
<result>
<code> <?=$errCode?> </code>
</result>
